import React, { useState, useEffect } from 'react';
import { Drawer, Descriptions, Tag, Empty, Spin, Alert, message } from 'antd';
import { LinkOutlined, CheckCircleOutlined, CloseCircleOutlined, WarningOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { 
    DubboConsumerDTO, 
    DubboProviderDetailDTO, 
    MatchStatus,
    getProviderDetail 
} from '../../../../services/dubboAnalysis';

interface ProviderDetailDrawerProps {
    visible: boolean;
    unitId: string;
    consumer: DubboConsumerDTO | null;
    onClose: () => void;
}

const ProviderDetailDrawer: React.FC<ProviderDetailDrawerProps> = ({ 
    visible, 
    unitId, 
    consumer, 
    onClose 
}) => {
    const navigate = useNavigate();
    const [loading, setLoading] = useState<boolean>(false);
    const [providerDetail, setProviderDetail] = useState<DubboProviderDetailDTO | null>(null);

    // 匹配状态配置
    const matchStatusConfig = {
        [MatchStatus.MATCHED]: {
            label: '已匹配',
            color: 'green',
            icon: <CheckCircleOutlined />,
        },
        [MatchStatus.VERSION_MISMATCH]: {
            label: '版本不匹配',
            color: 'orange',
            icon: <WarningOutlined />,
        },
        [MatchStatus.NOT_FOUND]: {
            label: '未找到提供者',
            color: 'red',
            icon: <CloseCircleOutlined />,
        },
    };

    // 加载 Provider 详情数据
    const loadProviderDetail = async (consumerConfigId: number) => {
        setLoading(true);
        try {
            const data = await getProviderDetail(unitId, consumerConfigId);
            setProviderDetail(data);
        } catch (error: any) {
            message.error(error.message || '加载 Provider 详情失败');
            setProviderDetail(null);
        } finally {
            setLoading(false);
        }
    };

    // 当抽屉打开且有 consumer 时加载数据
    useEffect(() => {
        if (visible && consumer) {
            loadProviderDetail(consumer.configId);
        } else {
            setProviderDetail(null);
        }
    }, [visible, consumer]);

    // 处理单元名称点击，跳转到提供者单元详情页面
    const handleUnitClick = (providerUnitId: string) => {
        navigate(`/unit/${providerUnitId}/dubbo`);
        onClose(); // 关闭抽屉
    };

    // 渲染未找到 Provider 的提示
    const renderNotFoundMessage = () => {
        const reasons = [
            '该服务的提供者尚未被扫描或录入系统',
            '服务分组或版本号配置不匹配',
            '提供者服务已下线或移除',
            '配置文件中的接口名称可能存在拼写错误',
        ];

        return (
            <Alert
                message="未找到提供者"
                description={
                    <div>
                        <div style={{ marginBottom: '12px', color: '#666' }}>
                            可能的原因：
                        </div>
                        <ul style={{ 
                            margin: 0, 
                            paddingLeft: '20px',
                            color: '#666',
                            lineHeight: '1.8'
                        }}>
                            {reasons.map((reason, index) => (
                                <li key={index}>{reason}</li>
                            ))}
                        </ul>
                        <div style={{ marginTop: '12px', color: '#999', fontSize: '13px' }}>
                            建议检查配置文件或联系服务提供方确认服务状态
                        </div>
                    </div>
                }
                type="warning"
                showIcon
                style={{ marginTop: '16px' }}
            />
        );
    };

    // 渲染版本不匹配的提示
    const renderVersionMismatchMessage = () => {
        return (
            <Alert
                message="版本不匹配"
                description={
                    <div style={{ color: '#666' }}>
                        找到了匹配的服务提供者，但版本号不一致。
                        这可能导致接口调用失败或行为异常，建议协调统一版本。
                    </div>
                }
                type="warning"
                showIcon
                style={{ marginTop: '16px' }}
            />
        );
    };

    return (
        <Drawer
            title={
                <div style={{ fontSize: '18px', fontWeight: 600 }}>
                    提供者详情
                </div>
            }
            placement="right"
            width={800}
            open={visible}
            onClose={onClose}
            destroyOnClose
        >
            {loading ? (
                <div style={{
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center',
                    minHeight: '300px'
                }}>
                    <Spin size="large" tip="加载中..." />
                </div>
            ) : providerDetail ? (
                <>
                    {/* Consumer 配置信息 */}
                    <div style={{
                        background: '#f5f5f5',
                        padding: '16px',
                        borderRadius: '8px',
                        marginBottom: '24px'
                    }}>
                        <div style={{
                            fontSize: '16px',
                            fontWeight: 600,
                            color: '#333',
                            marginBottom: '16px'
                        }}>
                            消费者配置信息
                        </div>
                        <Descriptions column={1} size="small">
                            <Descriptions.Item
                                label={<span style={{ fontWeight: 500 }}>接口全限定名</span>}
                            >
                                <span style={{ color: '#1890ff', fontFamily: 'monospace' }}>
                                    {providerDetail.interfaceFqn}
                                </span>
                            </Descriptions.Item>
                            <Descriptions.Item
                                label={<span style={{ fontWeight: 500 }}>服务分组</span>}
                            >
                                {providerDetail.serviceGroup ? (
                                    <Tag color="blue">{providerDetail.serviceGroup}</Tag>
                                ) : (
                                    <span style={{ color: '#999' }}>-</span>
                                )}
                            </Descriptions.Item>
                            <Descriptions.Item
                                label={<span style={{ fontWeight: 500 }}>版本号</span>}
                            >
                                {providerDetail.version ? (
                                    <Tag color="green">{providerDetail.version}</Tag>
                                ) : (
                                    <span style={{ color: '#999' }}>-</span>
                                )}
                            </Descriptions.Item>
                            <Descriptions.Item
                                label={<span style={{ fontWeight: 500 }}>超时时间</span>}
                            >
                                {providerDetail.timeout ? (
                                    <span>{providerDetail.timeout}</span>
                                ) : (
                                    <span style={{ color: '#999' }}>-</span>
                                )}
                            </Descriptions.Item>
                            <Descriptions.Item
                                label={<span style={{ fontWeight: 500 }}>配置文件</span>}
                            >
                                <div style={{ fontFamily: 'monospace', fontSize: '12px' }}>
                                    {providerDetail.filePath}
                                    {providerDetail.lineNumber && (
                                        <span style={{ color: '#999', marginLeft: '8px' }}>
                                            (行 {providerDetail.lineNumber})
                                        </span>
                                    )}
                                </div>
                            </Descriptions.Item>
                        </Descriptions>
                    </div>

                    {/* Provider 信息 */}
                    <div>
                        <div style={{
                            fontSize: '16px',
                            fontWeight: 600,
                            color: '#333',
                            marginBottom: '16px',
                            display: 'flex',
                            alignItems: 'center',
                            gap: '12px'
                        }}>
                            <span>提供者信息</span>
                            <Tag 
                                color={matchStatusConfig[providerDetail.matchStatus as MatchStatus].color}
                                icon={matchStatusConfig[providerDetail.matchStatus as MatchStatus].icon}
                                style={{ fontSize: '14px', padding: '4px 12px' }}
                            >
                                {matchStatusConfig[providerDetail.matchStatus as MatchStatus].label}
                            </Tag>
                        </div>

                        {providerDetail.matchStatus === MatchStatus.MATCHED && providerDetail.provider ? (
                            <div style={{
                                background: '#fff',
                                padding: '16px',
                                borderRadius: '8px',
                                border: '1px solid #d9f7be',
                                backgroundColor: '#f6ffed'
                            }}>
                                <Descriptions column={1} size="small">
                                    <Descriptions.Item
                                        label={<span style={{ fontWeight: 500 }}>单元名称</span>}
                                    >
                                        <a
                                            onClick={() => handleUnitClick(providerDetail.provider!.unitId)}
                                            style={{
                                                color: '#1890ff',
                                                cursor: 'pointer',
                                                fontWeight: 500,
                                                display: 'inline-flex',
                                                alignItems: 'center',
                                                gap: '4px'
                                            }}
                                        >
                                            <LinkOutlined style={{ fontSize: '12px' }} />
                                            {providerDetail.provider.unitName}
                                        </a>
                                    </Descriptions.Item>
                                    <Descriptions.Item
                                        label={<span style={{ fontWeight: 500 }}>应用名称</span>}
                                    >
                                        {providerDetail.provider.appName || (
                                            <span style={{ color: '#999' }}>-</span>
                                        )}
                                    </Descriptions.Item>
                                    <Descriptions.Item
                                        label={<span style={{ fontWeight: 500 }}>提供版本</span>}
                                    >
                                        {providerDetail.provider.providerVersion ? (
                                            <Tag color="green">{providerDetail.provider.providerVersion}</Tag>
                                        ) : (
                                            <span style={{ color: '#999' }}>-</span>
                                        )}
                                    </Descriptions.Item>
                                    <Descriptions.Item
                                        label={<span style={{ fontWeight: 500 }}>实现Bean</span>}
                                    >
                                        {providerDetail.provider.implBean ? (
                                            <span style={{ fontFamily: 'monospace', color: '#1890ff' }}>
                                                {providerDetail.provider.implBean}
                                            </span>
                                        ) : (
                                            <span style={{ color: '#999' }}>-</span>
                                        )}
                                    </Descriptions.Item>
                                    <Descriptions.Item
                                        label={<span style={{ fontWeight: 500 }}>实现类</span>}
                                    >
                                        {providerDetail.provider.implClass ? (
                                            <span style={{ fontFamily: 'monospace', fontSize: '12px' }}>
                                                {providerDetail.provider.implClass}
                                            </span>
                                        ) : (
                                            <span style={{ color: '#999' }}>-</span>
                                        )}
                                    </Descriptions.Item>
                                </Descriptions>
                            </div>
                        ) : providerDetail.matchStatus === MatchStatus.VERSION_MISMATCH && providerDetail.provider ? (
                            <>
                                <div style={{
                                    background: '#fff',
                                    padding: '16px',
                                    borderRadius: '8px',
                                    border: '1px solid #ffe7ba',
                                    backgroundColor: '#fffbe6'
                                }}>
                                    <Descriptions column={1} size="small">
                                        <Descriptions.Item
                                            label={<span style={{ fontWeight: 500 }}>单元名称</span>}
                                        >
                                            <a
                                                onClick={() => handleUnitClick(providerDetail.provider!.unitId)}
                                                style={{
                                                    color: '#1890ff',
                                                    cursor: 'pointer',
                                                    fontWeight: 500,
                                                    display: 'inline-flex',
                                                    alignItems: 'center',
                                                    gap: '4px'
                                                }}
                                            >
                                                <LinkOutlined style={{ fontSize: '12px' }} />
                                                {providerDetail.provider.unitName}
                                            </a>
                                        </Descriptions.Item>
                                        <Descriptions.Item
                                            label={<span style={{ fontWeight: 500 }}>应用名称</span>}
                                        >
                                            {providerDetail.provider.appName || (
                                                <span style={{ color: '#999' }}>-</span>
                                            )}
                                        </Descriptions.Item>
                                        <Descriptions.Item
                                            label={<span style={{ fontWeight: 500 }}>提供版本</span>}
                                        >
                                            {providerDetail.provider.providerVersion ? (
                                                <Tag color="orange">{providerDetail.provider.providerVersion}</Tag>
                                            ) : (
                                                <span style={{ color: '#999' }}>-</span>
                                            )}
                                        </Descriptions.Item>
                                        <Descriptions.Item
                                            label={<span style={{ fontWeight: 500 }}>实现Bean</span>}
                                        >
                                            {providerDetail.provider.implBean ? (
                                                <span style={{ fontFamily: 'monospace', color: '#1890ff' }}>
                                                    {providerDetail.provider.implBean}
                                                </span>
                                            ) : (
                                                <span style={{ color: '#999' }}>-</span>
                                            )}
                                        </Descriptions.Item>
                                        <Descriptions.Item
                                            label={<span style={{ fontWeight: 500 }}>实现类</span>}
                                        >
                                            {providerDetail.provider.implClass ? (
                                                <span style={{ fontFamily: 'monospace', fontSize: '12px' }}>
                                                    {providerDetail.provider.implClass}
                                                </span>
                                            ) : (
                                                <span style={{ color: '#999' }}>-</span>
                                            )}
                                        </Descriptions.Item>
                                    </Descriptions>
                                </div>
                                {renderVersionMismatchMessage()}
                            </>
                        ) : (
                            renderNotFoundMessage()
                        )}
                    </div>
                </>
            ) : (
                <Empty
                    description={
                        <span style={{ color: '#999' }}>
                            暂无数据
                        </span>
                    }
                />
            )}
        </Drawer>
    );
};

export default ProviderDetailDrawer;
